package com.tarzan.security.manager;

import com.tarzan.common.core.config.ConfigUtils;
import com.tarzan.common.core.utils.PropUtil;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Package com.tarzan.security.manager
 * @Title TokenManager
 * @Description TODO
 * @Author liujinshan
 * @CreateTime 2021/7/9 14:41
 */
@Component
public class TokenManager {
    private long tokenExpiration = 24*60*60*1000;
    private String tokenSignKey = "123456";
    private String header;

    public String createToken(String username) {
        String token = Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    public String getUserFromToken(String token) {
        String user = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        return user;
    }


    /**
     * 获取token
     * @param request
     * @return
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(PropUtil.getInstance().getConfig("token.header", PropUtil.DEFLAULT_NAME_SPACE));
        if (StringUtils.isNotEmpty(token) && token.startsWith(ConfigUtils.TOKEN_PREFIX)) {
            token = token.replace(ConfigUtils.TOKEN_PREFIX, "");
        }
        return token;
    }
}
